document.addEventListener('DOMContentLoaded', function() {
  // 添加登录相关变量
const loginForm = document.getElementById('loginForm');
const mainContent = document.getElementById('mainContent');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const loginBtn = document.getElementById('loginBtn');
const loginStatus = document.getElementById('loginStatus');

  const activityUrlInput = document.getElementById('activityUrl');
  const minPriceInput = document.getElementById('minPrice');
  const startBtn = document.getElementById('startBtn');
  const statusDiv = document.getElementById('status');
  const mallNameSpan = document.getElementById('mallName');
  const mallIdSpan = document.getElementById('mallId');


  // 初始禁用开始报名按钮
  startBtn.disabled = true; ///c测试改为false

  // 检查登录状态
  checkAuthStatus();
  
  // 登录按钮点击事件
  if(loginBtn) {
    loginBtn.addEventListener('click', login);
  }
  
  // 监听验证失败消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'authFailed') {
      console.log('验证失败消息:', JSON.stringify(request));
      // 显示登录界面
      // 显示登录表单
      if (loginForm) loginForm.style.display = 'block';
      if (mainContent) mainContent.style.display = 'none';
      
      // 显示错误消息
      if (loginStatus) loginStatus.textContent = request.message || '验证失败，请重新登录';
      
      // 确保登录按钮可用
      if (loginBtn && request.enableLoginButton) {
        loginBtn.disabled = false;
      }
    }
    return true;
  });

// 添加登录函数
async function login() {
  const username = usernameInput.value.trim();
  const password = passwordInput.value.trim();
  
  if (!username || !password) {
    loginStatus.textContent = '请输入用户名和密码';
    return;
  }
  
  loginBtn.disabled = true;
  loginStatus.textContent = '正在登录...';
  
  try {
   console.log('开始登录');
    // 调用后端API进行登录验证
    const response = await fetch('http://43.160.194.198:30322/api/login_plus', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username,
        password
      })
    });
 
    const data = await response.json();
   
    if (data.code === 1) {
      // 登录成功，保存授权信息

      chrome.storage.local.set({
        authToken: data.data.token,
        userId: data.data.mobile,
        lastLoginTime: Date.now(),
        expires_time: data.data.expires_time // 24小时后过期
      });
      
      // 通知background.js验证状态已更新
      chrome.runtime.sendMessage({action: 'verifyAuth', forceCheck: true}, (response) => {
        if (response && response.success) {
          // 显示主界面
          loginForm.classList.add('hidden');
          mainContent.classList.remove('hidden');
          
          // 获取店铺信息
          getShopInfo();
        } else {
          loginStatus.textContent = response?.error || '登录失败，请重试';
          loginBtn.disabled = false;
        }
      });
    } else {
      loginStatus.textContent = data.msg || '用户名或密码错误';
      loginBtn.disabled = false;
    }
  } catch (error) {
    console.error('登录过程出错:', error);
    loginStatus.textContent = '登录失败，请检查网络连接';
    loginBtn.disabled = false;
  }
}

// 检查登录状态
function checkAuthStatus() {
  chrome.runtime.sendMessage({action: 'checkAuthStatus'}, (response) => {
    if (chrome.runtime.lastError) {
      console.error('检查登录状态出错:', chrome.runtime.lastError);
      // 处理错误情况，默认显示登录界面
      if (loginForm) loginForm.classList.remove('hidden');
      if (mainContent) mainContent.classList.add('hidden');
      return;
    }
    
    if (response && response.success && response.authStatus) {
      // 已登录，显示主界面
      loginForm.classList.add('hidden');
      mainContent.classList.remove('hidden');
      
      // 获取店铺信息
      getShopInfo();
    } else {
      // 未登录，显示登录界面
      loginForm.classList.remove('hidden');
      mainContent.classList.add('hidden');
    }
  });
}
// 自动获取店铺信息
function getShopInfo() {
    startBtn.disabled = true;
    statusDiv.textContent = '正在获取店铺信息...';
      // 添加超时处理
   // 先检查验证状态
  chrome.runtime.sendMessage({action: 'checkAuthStatus'}, (authResponse) => {
    if (!authResponse || !authResponse.success || !authResponse.authStatus) {
      statusDiv.textContent = '验证失败，请重新登录';
      return;
    }
    
    // 验证通过，继续获取店铺信息
    // 先尝试直接获取店铺信息，如果已经有了就不需要刷新页面
    chrome.runtime.sendMessage({action: 'getShopInfo'}, (response) => {
      
      console.log('getShopInfo响应:', JSON.stringify(response));
      if (response && response.success && response.shopInfo) {
        console.log('已经获取到店铺信息，直接显示');
        // 已经有店铺信息，直接显示
        mallNameSpan.textContent = response.shopInfo.mallName || '-';
        mallIdSpan.textContent = response.shopInfo.mallId || '-';
        document.getElementById('registrationForm').style.display = 'block';
        startBtn.disabled = false;
        statusDiv.textContent = '店铺信息获取成功，请选择相关功能';
      } else {
        console.log('没有获取到店铺信息，尝试刷新页面');
        // 没有店铺信息，需要刷新页面触发网络请求
        tryRefreshAndGetInfo();
      }
    });
  });
}

  // 页面加载完成后自动获取店铺信息
  checkAuthStatus();
  
  // 尝试刷新页面并获取信息的函数
function tryRefreshAndGetInfo() {
  // 没有店铺信息，需要刷新页面触发网络请求
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs && tabs.length > 0 && tabs[0]) {
      chrome.tabs.reload(tabs[0].id);
      setTimeout(async () => {
        try {
          // 设置超时时间为10秒
          const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error('获取店铺信息超时')), 30000);
          });
          
          const responsePromise = new Promise((resolve) => {
            chrome.runtime.sendMessage({action: 'getShopInfo'}, (response) => {
              if (chrome.runtime.lastError) {
                console.error('获取店铺信息错误:', chrome.runtime.lastError);
                resolve({ success: false, error: chrome.runtime.lastError.message });
              } else {
                resolve(response);
              }
            });
          });
          
          // 使用Promise.race来处理超时
          const response = await Promise.race([responsePromise, timeoutPromise]);
          console.log("获取店铺信息响应:", JSON.stringify(response));
          
          if (response && response.success) {
            mallNameSpan.textContent = response.shopInfo.mallName || '-';
            mallIdSpan.textContent = response.shopInfo.mallId || '-';
            document.getElementById('registrationForm').style.display = 'block';
            startBtn.disabled = false;
            statusDiv.textContent = '店铺信息获取成功，请选择相关功能';
          } else {
            throw new Error(response?.error || '获取店铺信息失败');
          }
        } catch (error) {
          console.error('获取店铺信息失败:', error);
          mallNameSpan.textContent = '-';
          mallIdSpan.textContent = '-';
          statusDiv.textContent = `错误：${error.message}`;
          startBtn.disabled = true;
        }
      }, 2000); // 增加延迟时间，确保网络请求有足够时间触发
    } else {
      statusDiv.textContent = '获取店铺信息失败';
    }
  });
}

  
  // 监听店铺信息更新
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  //  console.log('sidebarjs收到消息:', JSON.stringify(request));
    if (request.action === 'updateShopInfo' && request.shopInfo) {
      mallNameSpan.textContent = request.shopInfo.mallName || '-';
      mallIdSpan.textContent = request.shopInfo.mallId || '-';
      document.getElementById('registrationForm').style.display = 'block';
      startBtn.disabled = false;
    } else if (request.action === 'registrationStatus') {
      const { success, total, failed } = request;
      statusDiv.textContent = `报名完成！成功：${total - failed}，失败：${failed}`;
      startBtn.disabled=false; 
        startBtn.textContent='开始自动报名';
    }
    else if (request.action === 'updateStatus') {
      // 处理状态更新消息
      statusDiv.textContent = request.message;
    }
     
    
    // 确保返回true以保持消息通道开放
    return true;
  });

  // 链接类型切换逻辑
document.querySelectorAll('input[name="urlType"]').forEach(radio => {
  radio.addEventListener('change', (e) => {
    const singleUrlSection = document.getElementById('singleUrlSection');
    const batchUrlSection = document.getElementById('batchUrlSection');
    const filterUrlSection = document.getElementById('filterUrlSection');
    
    // 隐藏所有链接输入区域
    singleUrlSection.style.display = 'none';
    batchUrlSection.style.display = 'none';
    filterUrlSection.style.display = 'none';
    
    // 根据选择显示对应区域
    if (e.target.value === '1') {
      singleUrlSection.style.display = 'block';
      // 清空其他输入
      document.getElementById('batchActivityUrls').value = '';
      document.getElementById('filteredActivities').innerHTML = '<option value="" disabled selected>请先获取活动列表</option>';
    } else if (e.target.value === '2') {
      batchUrlSection.style.display = 'block';
      // 清空其他输入
      document.getElementById('activityUrl').value = '';
      document.getElementById('filteredActivities').innerHTML = '<option value="" disabled selected>请先获取活动列表</option>';
    } else if (e.target.value === '3') {
      filterUrlSection.style.display = 'block';
      // 清空其他输入
      document.getElementById('activityUrl').value = '';
      document.getElementById('batchActivityUrls').value = '';
    }
  });
});

// 价格类型切换逻辑
document.querySelectorAll('input[name="priceType"]').forEach(radio => {
  radio.addEventListener('change', (e) => {
    const fixedSection = document.getElementById('fixedPriceSection');
    const randomSection = document.getElementById('randomPriceSection');
    
    if (e.target.value === '1') {
      fixedSection.style.display = 'block';
      randomSection.style.display = 'none';
      // 清空区间价格输入
      document.getElementById('minRandomPrice').value = '';
      document.getElementById('maxRandomPrice').value = '';
    } else {
      fixedSection.style.display = 'none';
      randomSection.style.display = 'block';
      // 清空固定价格输入
      document.getElementById('minPrice').value = '';
    }
  });
});

// 价格输入验证
function validatePrices() {
  const priceType = document.querySelector('input[name="priceType"]:checked').value;
  const fixedPriceError = document.getElementById('fixedPriceError');
  const randomPriceError = document.getElementById('randomPriceError');
  let isValid = true;

  if (priceType === '1') {
    const fixedPrice = parseFloat(document.getElementById('minPrice').value);
    if (!fixedPrice || fixedPrice <= 3.6) {
      fixedPriceError.textContent = '请输入有效的固定价格，必须大于3.6';
      isValid = false;
    } else {
      fixedPriceError.textContent = '';
    }
  } else {
    const minPrice = parseFloat(document.getElementById('minRandomPrice').value);
    const maxPrice = parseFloat(document.getElementById('maxRandomPrice').value);
    
    if (!minPrice || !maxPrice || minPrice <= 3.6 || maxPrice <= 0) {
      randomPriceError.textContent = '请输入有效的价格区间,最低价格3.6';
      isValid = false;
    } else if (minPrice >= maxPrice) {
      randomPriceError.textContent = '最小价格必须小于最大价格';
      isValid = false;
    } else {
      randomPriceError.textContent = '';
    }
  }
  
  return isValid;
}

  // 全局变量，用于存储筛选后的活动列表
  let globalFilteredActivities = [];

  // 获取活动列表按钮点击事件
  document.getElementById('fetchActivitiesBtn')?.addEventListener('click', async function() {
    const fetchStatusDiv = document.getElementById('fetchStatus');
    const filteredActivitiesSelect = document.getElementById('filteredActivities');
    
    fetchStatusDiv.textContent = '正在获取活动列表数据...';
    filteredActivitiesSelect.innerHTML = '<option value="" disabled selected>正在加载...</option>';
    
    try {
      // 验证token是否过期
    /*   const tokenValid = await new Promise(resolve => {
        chrome.storage.local.get(['authToken', 'expires_time'], function(result) {
          const now = Date.now();
          if (!result.authToken || !result.expires_time || now >= (result.expires_time*1000)) {
            fetchStatusDiv.textContent = '登录已过期，请重新登录';
            loginForm.classList.remove('hidden');
            mainContent.classList.add('hidden');
            resolve(false);
          } else {
            resolve(true);
          }
        });
      }); */
      const tokenValid  =await verifyTokenValidity()

      if (!tokenValid) return;
      
      // 获取筛选条件
      const activityTypeSelect = document.getElementById('activityType');
      const selectedOption = activityTypeSelect.options[activityTypeSelect.selectedIndex];
     // const activityType = parseInt(document.getElementById('activityType').value);
      const activityType = parseInt(selectedOption.value);
      const activityTypeName = selectedOption.textContent;
      const enrollCountFilter = document.getElementById('enrollCountFilter').checked;
      const durationDays = parseInt(document.getElementById('durationDays').value) || 0;
      const endTimeDays = parseInt(document.getElementById('endTimeDays').value) || 0;
      //const startTimeDays = parseInt(document.getElementById('startTimeDays').value) || 0;
      console.log('选中的活动类型:', activityType, activityTypeName);
      // 调用API获取活动列表
      const response = await new Promise((resolve) => {
        chrome.runtime.sendMessage({
          action: 'fetchActivityList',
          url: 'https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/activity/list'

        }, (response) => {
          if (chrome.runtime.lastError) {
            resolve({ success: false, error: chrome.runtime.lastError.message });
          } else {
            resolve(response);
          }
        });
      });
      
      if (!response.success || !response.data || !response.data.result) {
        fetchStatusDiv.textContent = `获取活动列表失败: ${response.error || '未知错误'}`;
        return;
      }
      
      // 处理API返回的数据
      const activityList = response.data.result.activityList || [];
      globalFilteredActivities = [];
      
      // 遍历活动列表，应用筛选条件
      activityList.forEach(activity => {
        // 筛选活动类型
        if (activity.activityType !== activityType) return;
        
        // 获取活动主题列表
        const thematicList = activity.thematicList || [];
        
        // 筛选符合条件的主题
        thematicList.forEach(thematic => {
          // 筛选报名人数条件
          if (enrollCountFilter && thematic.enrolledCount >= thematic.canEnrollTotal) return;
          
          // 筛选活动持续天数
          if (durationDays > 0 && thematic.durationDays !== durationDays) return;
          
          // 筛选距离结束时间的天数
          if (endTimeDays > 0) {
            const endTimeDate = new Date(thematic.endTime);
            const currentDate = new Date();
            const diffTime = endTimeDate.getTime() - currentDate.getTime();
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            if (diffDays >= endTimeDays) return;
          }
          // 筛选活动开始时间
          // 获取开始时间筛选值，如果未选择则默认为已开始活动
          let startTimeFilter = '1'; // 默认为已开始活动
          const startTimeFilterElement = document.querySelector('input[name="startTimeFilter"]:checked');
         // console.log('startTimeFilterElement:', startTimeFilterElement);
          if (startTimeFilterElement) {
            startTimeFilter = startTimeFilterElement.value;
          }
          const startTimeDate = new Date(thematic.startTime);
          const currentDate = new Date();
          
          if (startTimeFilter === '1') { // 已开始活动
            if (startTimeDate > currentDate) return;
          } else if (startTimeFilter === '2') { // 未开始活动
            if (startTimeDate <= currentDate) return;
          }
          
          // 符合所有条件，添加到结果列表
          globalFilteredActivities.push({
            activityThematicId: thematic.activityThematicId,
            activityThematicName: thematic.activityThematicName,
            enrolledCount: thematic.enrolledCount,
            canEnrollTotal: thematic.canEnrollTotal,
            durationDays: thematic.durationDays,
            startTime: new Date(thematic.startTime).toLocaleDateString(),
            endTime: new Date(thematic.endTime).toLocaleDateString()
          });
        });
      });
      
      // 更新筛选结果下拉列表
      filteredActivitiesSelect.innerHTML = '';
      
      if (globalFilteredActivities.length === 0) {
        filteredActivitiesSelect.innerHTML = '<option value="" disabled selected>没有找到符合条件的活动</option>';
        fetchStatusDiv.textContent = '没有找到符合条件的活动';
      } else {
        // 按活动主题ID排序
        globalFilteredActivities.sort((a, b) => b.activityThematicId - a.activityThematicId);
        
        // 添加选项到下拉列表
        globalFilteredActivities.forEach(activity => {
          const option = document.createElement('option');
          option.value = activity.activityThematicId;
          option.textContent = `${activity.activityThematicName} (${activity.enrolledCount}/${activity.canEnrollTotal}) ${activity.durationDays}天 ${activity.startTime}-${activity.endTime}`;
          option.title = `活动ID: ${activity.activityThematicId}\n报名人数: ${activity.enrolledCount}/${activity.canEnrollTotal}\n持续天数: ${activity.durationDays}天\n时间: ${activity.startTime} 至 ${activity.endTime}`;
          filteredActivitiesSelect.appendChild(option);
        });
        
        fetchStatusDiv.textContent = `找到 ${globalFilteredActivities.length} 个符合条件的活动`;
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      fetchStatusDiv.textContent = `获取失败: ${error.message}`;
      filteredActivitiesSelect.innerHTML = '<option value="" disabled selected>获取活动列表失败</option>';
    }
  });
  
  // 批量轮询报名按钮点击事件
  document.getElementById('batchEnrollBtn')?.addEventListener('click', async function() {
    const batchEnrollStatusDiv = document.getElementById('batchEnrollStatus');
    
    // 验证是否有活动可报名
    if (globalFilteredActivities.length === 0) {
      batchEnrollStatusDiv.textContent = '没有可报名的活动，请先获取活动列表';
      return;
    }
    
    // 添加价格验证
    if (!validatePrices()) {
      return;
    }
    
    // 添加确认弹窗
    if (!confirm(`确定要批量轮询报名所有 ${globalFilteredActivities.length} 个活动吗？请再次确认价格和库存设置。`)) {
      batchEnrollStatusDiv.textContent = '已取消批量轮询报名';
      return;
    }
    
    // 验证token是否过期
  /*   const tokenValid = await new Promise(resolve => {
      chrome.storage.local.get(['authToken', 'expires_time'], function(result) {
        const now = Date.now();
        if (!result.authToken || !result.expires_time || now >= (result.expires_time*1000)) {
          batchEnrollStatusDiv.textContent = '登录已过期，请重新登录';
          loginForm.classList.remove('hidden');
          mainContent.classList.add('hidden');
          resolve(false);
        } else {
          resolve(true);
        }
      });
    }); */
    const tokenValid  =await verifyTokenValidity()


    if (!tokenValid) return;
    
    // 禁用按钮，防止重复点击
    this.disabled = true;
    this.textContent = '正在轮询报名中...';
    
    // 准备价格数据
    const priceType = document.querySelector('input[name="priceType"]:checked').value;
    const priceData = priceType === '1' 
      ? { fixedPrice: parseFloat(document.getElementById('minPrice').value) }
      : {
          minRandomPrice: parseFloat(document.getElementById('minRandomPrice').value),
          maxRandomPrice: parseFloat(document.getElementById('maxRandomPrice').value)
        };
    
    // 获取活动报名库存值
    const activityStock = parseInt(document.getElementById('activityStock').value);
    const minPrice = parseFloat(minPriceInput.value) || 3.6;
    // 开始轮询报名
    let successCount = 0;
    let failedCount = 0;
    
    batchEnrollStatusDiv.textContent = `开始轮询报名，共 ${globalFilteredActivities.length} 个活动...`;
    
    // 逐个报名活动
    for (let i = 0; i < globalFilteredActivities.length; i++) {
      const activity = globalFilteredActivities[i];
      const activityUrl = `https://agentseller.temu.com/activity/marketing-activity/detail-new?type=13&thematicId=${activity.activityThematicId}`;
      
      batchEnrollStatusDiv.textContent = `正在报名第 ${i+1}/${globalFilteredActivities.length} 个活动: ${activity.activityThematicName}`;
      statusDiv.textContent = `正在报名: ${activity.activityThematicName}`;
      
      try {
        console.log("准备发送报名请求:", activityUrl);
        //https://seller.kuajingmaihuo.com/activity/marketing-activity/detail-new?type=13&thematicId=250325325680924
        // 发送报名请求
        const response = await new Promise((resolve) => {
          chrome.runtime.sendMessage({
            action: 'startRegistration',
            activityUrl: activityUrl,
            minPrice: minPrice,
            priceType: priceType,
            priceData: priceData,
            activityStock: activityStock
          }, (response) => {
            if (chrome.runtime.lastError) {
              resolve({ success: false, error: chrome.runtime.lastError.message });
            } else {
              resolve(response);
            }
          });
        });
        console.log("报名响应:", JSON.stringify(response));
        // 处理报名结果
        if (response.success) {
          successCount++;
          batchEnrollStatusDiv.textContent = `已完成 ${i+1}/${globalFilteredActivities.length} 个活动，成功: ${successCount}，失败: ${failedCount}`;
        } else {
          failedCount++;
          batchEnrollStatusDiv.textContent = `已完成 ${i+1}/${globalFilteredActivities.length} 个活动，成功: ${successCount}，失败: ${failedCount} - 最近失败: ${response.error || '未知错误'}`;
        }
        
       
        // 添加延迟，避免请求过快
        const randomDelay =  Math.floor(Math.random() * (45000 - 15000 + 1)) + 15000;
        await new Promise(resolve => setTimeout(resolve, randomDelay));
      } catch (error) {
        failedCount++;
        batchEnrollStatusDiv.textContent = `已完成 ${i+1}/${globalFilteredActivities.length} 个活动，成功: ${successCount}，失败: ${failedCount} - 错误: ${error.message}`;
        const errorRandomDelay =  Math.floor(Math.random() * (45000 - 15000 + 1)) + 15000;
        await new Promise(resolve => setTimeout(resolve, errorRandomDelay));
      }
    }
    
    // 报名完成，恢复按钮状态
    this.disabled = false;
    this.textContent = '批量轮询报名所有活动';
    
    // 更新最终状态
    batchEnrollStatusDiv.textContent = `轮询报名完成！共 ${globalFilteredActivities.length} 个活动，成功: ${successCount}，失败: ${failedCount}`;
    statusDiv.textContent = `批量轮询报名完成！成功: ${successCount}，失败: ${failedCount}`;
  });

  startBtn.addEventListener('click', async function() {
    console.log('开始按钮点击');
     // 添加价格验证
     if (!validatePrices()) {
      return;
    }
    
    // 添加确认弹窗
    if (!confirm('请再次确认价格和库存后再开始自动报名')) {
      statusDiv.textContent = '已取消自动报名';
      return;
    }
    // 验证token是否过期
    /* const tokenValid = await new Promise(resolve => {
      chrome.storage.local.get(['authToken', 'expires_time'], function(result) {
        const now = Date.now();
        if (!result.authToken || !result.expires_time || now >= (result.expires_time*1000)) {
          statusDiv.textContent = '登录已过期，请重新登录';
          loginForm.classList.remove('hidden');
          mainContent.classList.add('hidden');
          resolve(false);
        } else {
          resolve(true);
        }
      });
    }); */
    const tokenValid  =await verifyTokenValidity()

    if (!tokenValid) return;

    // 获取链接类型
    const urlType = document.querySelector('input[name="urlType"]:checked').value;
    const url = activityUrlInput.value.trim();
    

      // 单个链接模式
     
      if (!url) {
        statusDiv.textContent = '请输入活动报名链接';
        return;
      }
     // urls.push(url);
    

    try {
      const minPrice = parseFloat(minPriceInput.value) || 3.6;
      const priceType = document.querySelector('input[name="priceType"]:checked').value;
      // 根据价格类型准备价格数据
      const priceData = priceType === '1' 
        ? { fixedPrice: parseFloat(document.getElementById('minPrice').value) }
        : {
            minRandomPrice: parseFloat(document.getElementById('minRandomPrice').value),
            maxRandomPrice: parseFloat(document.getElementById('maxRandomPrice').value)
          };
      
      // 获取活动报名库存值
      const activityStock = parseInt(document.getElementById('activityStock').value);
      console.log('准备的价格数据:', priceData);
      console.log('活动报名库存:', activityStock);
      console.log('活动链接:', url);
      
      // 发送消息给后台脚本
      const response = await new Promise((resolve) => {
        chrome.runtime.sendMessage({
          action: 'startRegistration',
          activityUrl: url,  // 传递链接数组
          minPrice: minPrice,
          priceType: priceType,
          priceData: priceData,
          activityStock: activityStock
        }, (response) => {
          if (chrome.runtime.lastError) {
            resolve({ success: false, error: chrome.runtime.lastError.message });
          } else {
            resolve(response);
          }
        });
      });

      if (response.success) {
        console.log(response)
        startBtn.disabled = true; 
        startBtn.textContent = '正在报名,请等待...';
       
      } else {
        statusDiv.textContent = `错误：${response.error}`;
      }
    } catch (error) {
      statusDiv.textContent = `发生错误：${error.message}`;
    }
  });
});
// 获取当前页面URL按钮的事件监听
document.getElementById('getUrlBtn').addEventListener('click', function() {
  // 使用chrome.tabs API获取当前活动标签页的URL
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    const currentUrl = tabs[0].url;
    document.getElementById('activityUrl').value = currentUrl;
  });
});
// 选项卡切换功能
document.addEventListener('DOMContentLoaded', function() {
  const tabs = document.querySelectorAll('.tab');
  const tabContents = document.querySelectorAll('.tab-content');
  
  tabs.forEach(tab => {
    tab.addEventListener('click', function() {
      // 移除所有选项卡的活动状态
      tabs.forEach(t => {
        t.classList.remove('active');
        t.style.backgroundColor = '#eee';
        t.style.color = '#000';
      
      });
      
      // 添加当前选项卡的活动状态
      this.classList.add('active');
      this.style.backgroundColor = '#4CAF50';
      this.style.color = '#fff';
      
      // 隐藏所有内容区域
      tabContents.forEach(content => {
        content.style.display = 'none';
      });
      
      // 显示当前选项卡对应的内容区域
      const tabId = this.getAttribute('data-tab');
      const activeContent = document.querySelector(`.tab-content[data-tab="${tabId}"]`);
      if (activeContent) {
        activeContent.style.display = 'block';
      }
    });
  });
});
// 活动商品导出功能
document.getElementById('exportProductsBtn')?.addEventListener('click', async function() {
  const exportStatusDiv = document.getElementById('exportStatus');
  exportStatusDiv.textContent = '正在检查页面...';
  
  try {
    // 获取当前页面URL
    const tabs = await new Promise(resolve => {
      chrome.tabs.query({active: true, currentWindow: true}, resolve);
    });
    
    const currentUrl = tabs[0].url;
    
    // 检查是否在正确的页面
    if (!currentUrl.includes('agentseller.temu.com/activity/marketing-activity/log')) {
      exportStatusDiv.textContent = '请先进入活动记录管理页面:agentseller.temu.com/activity/marketing-activity/log';
      return;
    }
    
    exportStatusDiv.textContent = '正在获取活动记录数据...';
    
    // 获取所有活动商品数据
    const allProducts = await fetchAllProducts();
    
    if (allProducts.length === 0) {
      exportStatusDiv.textContent = '未找到活动记录数据';
      return;
    }
    
    // 生成并下载Excel文件
    exportToExcel(allProducts);
    
    exportStatusDiv.textContent = `成功导出 ${allProducts.length} 个活动商品数据`;
  } catch (error) {
    console.error('导出活动商品失败:', error);
    exportStatusDiv.textContent = `导出失败: ${error.message}`;
  }
});

// 获取所有活动商品数据
async function fetchAllProducts() {
  const allProducts = [];
  let pageNo = 1;
  let hasMore = true;
  const pageSize = 40;
  
  while (hasMore) {
    try {
      // 添加延迟，避免请求过快
      const randomDelay = Math.floor(Math.random() * (45000 - 15000 + 1)) + 15000;
      await new Promise(resolve => setTimeout(resolve, randomDelay));
      
      const response = await fetchProductsPage(pageNo, pageSize);
      
      if (!response || !response.result || !response.result.list) {
        hasMore = false;
        continue;
      }
      
      const { total, list } = response.result;
      
      // 添加当前页的商品到结果中
      list.forEach(product => {
        allProducts.push({
          goodsId: product.goodsId,
          productId: product.productId,
          activityThematicName: product.activityThematicName,
          activityTypeName: product.activityTypeName,
          productName: product.productName,
      
        });
      });
      
      // 判断是否还有更多页
      const totalPages = Math.ceil(total / pageSize);
      hasMore = pageNo < totalPages;
      pageNo++;
      
      // 更新状态
      document.getElementById('exportStatus').textContent = `正在获取数据: ${allProducts.length}/${total}`;
    } catch (error) {
      console.error(`获取第${pageNo}页数据失败:`, error);
      hasMore = false;
    }
  }
  
  return allProducts;
}

// 获取单页活动商品数据
async function fetchProductsPage(pageNo, pageSize) {
  // 添加随机延迟，模拟人工操作，避免被系统识别为机器人

  const randomDelay = Math.floor(Math.random() * (45000 - 15000 + 1)) + 15000;
  await new Promise(resolve => setTimeout(resolve, randomDelay));
  
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage({
      action: 'fetchActivityProducts',
      url: 'https://agentseller.temu.com/api/kiana/gambit/marketing/enroll/list',
      data: {
        pageNo,
        pageSize
      }
    }, response => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else if (response.error) {
        reject(new Error(response.error));
      } else {
        resolve(response);
      }
    });
  });
}

// 导出到Excel
function exportToExcel(products) {
  // 创建工作表数据
  const worksheet = XLSX.utils.json_to_sheet(products);
  
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "活动商品");
  
  // 生成Excel文件并下载
  const fileName = `TEMU活动商品_${new Date().toISOString().split('T')[0]}.xlsx`;
  XLSX.writeFile(workbook, fileName);
}
//
async function verifyTokenValidity() {
  const statusDiv = document.getElementById('status');
  const loginForm = document.getElementById('loginForm');
const mainContent = document.getElementById('mainContent');
  try {
    // 从本地存储获取token信息
    const tokenValid = await new Promise(resolve => {
      chrome.storage.local.get(['authToken', 'expires_time'], async function(result) {
        const now = Date.now();
        
        // 检查本地token是否存在和过期
        if (!result.authToken || !result.expires_time || now >= (result.expires_time*1000)) {
          statusDiv.textContent = '登录已过期，请重新登录';
          loginForm.classList.remove('hidden');
          mainContent.classList.add('hidden');
         // 添加弹窗提醒
         alert('登录已过期/授权到期，系统将自动刷新页面，请重新登录！');
          
         // 延迟执行刷新，确保用户能看到提示
         setTimeout(() => {
           chrome.runtime.reload();
         }, 1000);
         
          resolve(false);
          return;
        }
        
        // 在线验证token
        try {
          const response = await fetch('http://43.160.194.198:30322/api/verify_token', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'token': `${result.authToken}`
            }
          });
          
          const data = await response.json();
          
          if (data.code !== 1) {
            // token无效，清除本地存储
            chrome.storage.local.remove(['authToken', 'userId', 'expires_time']);
            statusDiv.textContent = '登录已失效，请重新登录';
            loginForm.classList.remove('hidden');
            mainContent.classList.add('hidden');
     // 添加弹窗提醒
     alert('登录已过期/授权到期，系统将自动刷新页面，请重新登录！');
     // 延迟执行刷新，确保用户能看到提示
     setTimeout(() => {
       chrome.runtime.reload();
     }, 1000);
            resolve(false);
          } else {
            resolve(true);
          }
        } catch (error) {
          console.error('验证token时发生错误:', error);
          statusDiv.textContent = '验证失败，请检查网络连接';
          resolve(false);
        }
      });
    });
    
    return tokenValid;
  } catch (error) {
    console.error('验证过程发生错误:', error);
    return false;
  }
}

